<template>
  <div class="main-layout">
    <!-- 左侧会话列表 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2>AI助手</h2>
        <button class="new-chat-btn" @click="createNewSession">
          ✚ 新建对话
        </button>
      </div>
      <SessionList 
        :sessions="sessions"
        :current-session-id="currentSessionId"
        @select-session="selectSession"
        @delete-session="deleteSession"
      />
    </div>
    
    <!-- 中间媒体展示区 -->
    <div class="media-center">
      <MediaDisplay />
    </div>
    
    <!-- 右侧聊天区域 -->
    <div class="chat-panel">
      <ChatArea 
        :current-session="currentSession"
        :conversations="conversations"
        :loading="chatLoading"
        @send-message="sendMessage"
      />
    </div>
  </div>
</template>

<script>
import SessionList from './SessionList.vue'
import ChatArea from './ChatArea.vue'
import MediaDisplay from './MediaDisplay.vue'
import { sessionAPI, chatAPI } from '../api/index.js'

export default {
  name: 'MainLayout',
  components: {
    SessionList,
    ChatArea,
    MediaDisplay
  },
  data() {
    return {
      sessions: [],
      currentSessionId: null,
      currentSession: null,
      loading: false,
      // 每个会话独立维护自己的消息状态 - 改用普通对象确保Vue响应式
      sessionMessages: {} // key: sessionId, value: { messages: [], loading: false }
    }
  },
  computed: {
    // 当前会话的对话列表
    conversations() {
      if (!this.currentSessionId || !this.sessionMessages[this.currentSessionId]) {
        return []
      }
      return this.sessionMessages[this.currentSessionId].messages
    },
    // 当前会话是否在加载中
    chatLoading() {
      if (!this.currentSessionId || !this.sessionMessages[this.currentSessionId]) {
        return false
      }
      return this.sessionMessages[this.currentSessionId].loading
    }
  },
  async mounted() {
    await this.loadSessions()
  },
  methods: {
    // 加载会话列表
    async loadSessions() {
      try {
        this.loading = true
        const response = await sessionAPI.getSessions()
        if (response.code === 200) {
          this.sessions = response.data.sessions
          // 自动选择最新的会话（第一个会话）
          if (this.sessions.length > 0 && !this.currentSessionId) {
            const firstSession = this.sessions[0]
            this.currentSessionId = firstSession.id
            this.currentSession = firstSession
            // 异步加载对话历史，不阻塞初始化
            this.loadConversations(firstSession.id)
          }
        }
      } catch (error) {
        console.error('加载会话列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 创建新会话
    async createNewSession() {
      console.log('🔄 开始创建新会话...')
      try {
        const startTime = Date.now()
        const response = await sessionAPI.createSession()
        const endTime = Date.now()
        
        console.log(`⏱️ 创建会话耗时: ${endTime - startTime}ms`, response)
        
        if (response && response.code === 200) {
          const newSession = response.data
          console.log('✅ 新会话创建成功:', newSession)
          
          this.sessions.unshift(newSession)
          
          // 立即切换到新会话，不等待任何异步操作
          this.currentSessionId = newSession.id
          this.currentSession = newSession
          
          // 为新会话初始化空的消息状态
          this.sessionMessages[newSession.id] = {
            messages: [],
            loading: false
          }
        } else {
          console.warn('⚠️ 创建会话响应异常:', response)
        }
      } catch (error) {
        console.error('❌ 创建会话失败:', error)
      }
    },
    
    // 选择会话
    selectSession(session) {
      this.currentSessionId = session.id
      this.currentSession = session
      
      // 如果还没有加载过这个会话的消息，则异步加载（不阻塞UI）
      if (!this.sessionMessages[session.id]) {
        this.loadConversations(session.id)
      }
    },
    
    // 加载对话历史
    async loadConversations(sessionId) {
      try {
        const response = await sessionAPI.getConversations(sessionId)
        if (response.code === 200) {
          // 为该会话设置消息状态 - Vue 3 可以直接赋值
          this.sessionMessages[sessionId] = {
            messages: response.data.chats || [],
            loading: false
          }
        }
      } catch (error) {
        console.error('加载对话历史失败:', error)
        this.sessionMessages[sessionId] = {
          messages: [],
          loading: false
        }
      }
    },
    
    // 发送消息
    async sendMessage(message) {
      if (!this.currentSessionId || !message.trim()) return
      
      const sessionId = this.currentSessionId
      
      // 确保该会话有消息状态
      if (!this.sessionMessages[sessionId]) {
        this.sessionMessages[sessionId] = {
          messages: [],
          loading: false
        }
      }
      
      const sessionState = this.sessionMessages[sessionId]
      
      // 添加用户消息到该会话
      const userMessage = {
        id: `temp-${Date.now()}`,
        user_input: message,
        agent_response: null,
        created_at: new Date().toISOString(),
        isWaitingReply: true // 标记为等待回复
      }
      sessionState.messages.push(userMessage)
      
      try {
        // 设置该会话为加载状态
        sessionState.loading = true
        
        // 发送到后端
        const response = await chatAPI.chat(message, sessionId)
        
        if (response.code === 200) {
          // 更新消息状态
          userMessage.agent_response = response.data.response
          userMessage.isWaitingReply = false
        } else {
          // 请求失败，移除这条消息
          const index = sessionState.messages.findIndex(msg => msg.id === userMessage.id)
          if (index > -1) {
            sessionState.messages.splice(index, 1)
          }
        }
      } catch (error) {
        console.error('发送消息失败:', error)
        // 请求失败，移除这条消息
        const index = sessionState.messages.findIndex(msg => msg.id === userMessage.id)
        if (index > -1) {
          sessionState.messages.splice(index, 1)
        }
      } finally {
        // 清除该会话的加载状态
        sessionState.loading = false
      }
    },
    
    // 删除会话
    async deleteSession(sessionId) {
      try {
        const response = await sessionAPI.deleteSession(sessionId)
        if (response.code === 200) {
          this.sessions = this.sessions.filter(s => s.id !== sessionId)
          // 清理该会话的消息状态
          delete this.sessionMessages[sessionId]
          if (this.currentSessionId === sessionId) {
            this.currentSessionId = null
            this.currentSession = null
          }
        }
      } catch (error) {
        console.error('删除会话失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.main-layout {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h2 {
  color: #2d3436;
  font-size: 20px;
  margin-bottom: 15px;
}

.new-chat-btn {
  width: 100%;
  padding: 12px;
  background: #00b894;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.new-chat-btn:hover {
  background: #00a085;
}

.media-center {
  flex: 3;
  background: #fff;
  border-right: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 0;
}

.chat-panel {
  flex: 7;
  background: #fff;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

/* 平板适配 */
@media (max-width: 1024px) {
  .main-layout {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }
  
  .media-center {
    height: 300px;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
  }
  
  .chat-panel {
    width: 100%;
    flex: 1;
  }
}

/* 手机适配 */
@media (max-width: 768px) {
  .sidebar {
    height: 150px;
  }
  
  .media-center {
    height: 200px;
  }
  
  .sidebar-header {
    padding: 15px;
  }
  
  .sidebar-header h2 {
    font-size: 18px;
    margin-bottom: 10px;
  }
}
</style>